<template>
	<view>
		<back :showBackText="false" customClass="bg-gradual-blue text-white" title="编辑资料"></back>
		<view v-if="isLoad" class="content-wrapper">
			<!-- 头像选择区域 -->
			<view class="avatar-section">
				<button class="avatar-button" open-type="chooseAvatar" @chooseavatar="avatarInputTap">
					<view class="cu-avatar round xl" :style="'background-image:url('+avatarInputVal+');'">
					</view>
					<view class="avatar-hint">点击更换头像</view>
				</button>
			</view>
			
			<!-- 表单区域 -->
			<view class="form-section">
				<view class="cu-form-group radius shadow-warp">
					<view class="title"><text class="cuIcon-my text-blue margin-right-xs"></text>昵称</view>
					<input @input="nicknameInputTap" type="nickname" maxlength="20" placeholder="填入要修改的昵称"
						:value="nicknameInputVal" />
				</view>
				<view class="cu-form-group radius shadow-warp">
					<view class="title"><text class="cuIcon-mobile text-blue margin-right-xs"></text>手机</view>
					<input v-if="user.mobile" disabled :value="user.mobile" />
					<button v-else open-type="getPhoneNumber" @getphonenumber="wxPhoneBindTap" class="cu-btn bg-blue sm radius">
						绑定手机号
					</button>
				</view>
			</view>
			
			<!-- 按钮区域 -->
			<view class="button-section">
				<button @tap="submitTap" class="cu-btn bg-gradual-blue lg radius shadow-blur">保存资料</button>
				<button @tap="cancelTap" class="cu-btn bg-grey lg radius shadow-blur">取消修改</button>
			</view>
			
			<adfootbanner></adfootbanner>
		</view>
		
		<!-- 用于图片压缩的canvas，不设置固定宽高 -->
		<canvas canvas-id="compressCanvas" id="compressCanvas" style="position: absolute; left: -9999px; top: -9999px;"></canvas>
	</view>
</template>

<script>
	import {
		upload,
		post
	} from "@/common/js/http.js";
	import { isSet } from "@/common/js/util.js";
	let app = getApp();
	let that = null;
	export default {
		data() {
			return {
				isLoad: false,
				user: {},
				avatarInputVal: '',
				nicknameInputVal: '',
			};
		},
		onLoad(options) {
			that = this;
			let userInfo = app.globalData.config.storage.getUserInfoData();
			that.user = userInfo;
			that.isLoad = true;
			that.avatarInputVal = userInfo.avatar;
			that.nicknameInputVal = userInfo.nickname;
		},
		methods: {
			// 压缩图片方法
			compressImage(path) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: path,
						success: (res) => {
							let width = res.width;
							let height = res.height;
							let scale = width / height;
							
							// 设置最大宽度为800px，保持原比例
							let targetWidth = Math.min(width, 800);
							let targetHeight = targetWidth / scale;
							
							// 创建canvas上下文
							const ctx = uni.createCanvasContext('compressCanvas', that);
							
							// 设置canvas尺寸与目标图片尺寸一致
							ctx.canvas = {
								width: targetWidth,
								height: targetHeight
							};
							
							// 清空画布
							ctx.clearRect(0, 0, targetWidth, targetHeight);
							
							// 绘制图片到canvas，确保绘制整张图片
							ctx.drawImage(path, 0, 0, targetWidth, targetHeight);
							ctx.draw(false, () => {
								// 将canvas转为图片
								uni.canvasToTempFilePath({
									canvasId: 'compressCanvas',
									x: 0,
									y: 0,
									width: targetWidth,
									height: targetHeight,
									destWidth: targetWidth,
									destHeight: targetHeight,
									quality: 0.8, // 压缩质量，范围0-1
									success: (res) => {
										resolve(res.tempFilePath);
									},
									fail: (err) => {
										console.error('压缩图片失败:', err);
										reject(err);
									}
								}, that);
							});
						},
						fail: (err) => {
							console.error('获取图片信息失败:', err);
							reject(err);
						}
					});
				});
			},
			avatarInputTap(options) {
				uni.showModal({
					content: '确认使用此头像?',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							});
							
							try {
								// 压缩图片
								const compressedPath = await that.compressImage(options.detail.avatarUrl);
								
								// 上传压缩后的图片
								let res = await upload('file',
									compressedPath, {
										'app': 'learnAppTemp',
										'sign': app.globalData.getTimestamp()
									});
								let avatar = res.data;
								app.globalData.service.updateUser({
									avatar: avatar
								});
								that.user.avatar = avatar;
								app.globalData.config.storage.setUserInfoData(that.user);
								uni.hideLoading();
							} catch (error) {
								console.error('头像处理失败:', error);
								uni.hideLoading();
								uni.showToast({
									title: '头像处理失败',
									icon: 'none'
								});
							}
						}
					}
				});
				that.avatarInputVal = options.detail.avatarUrl;
			},
			nicknameInputTap(options) {
				that.nicknameInputVal = options.detail.value;
			},
			// 微信手机号快捷绑定
			wxPhoneBindTap(options) {
				if (!isSet(options.detail.code)) {
					return;
				}
				uni.login({
					success(res) {
						let data = {
							code: res.code,
							wx_phone_code: options.detail.code
						};
						post('user/bindWxMobile', data)
							.then((t) => {
								if (t.code == 1) {
									console.log(t);
									that.user.mobile = t.data.mobile;
									app.globalData.config.storage.setUserInfoData(that.user);
								} else {
									app.showToast(t.message);
								}
							})
							.catch((t) => {
								app.showToast('微信手机号绑定异常');
							});
					}
				});
			},
			async submitTap(options) {
				let res = await app.globalData.service.updateUser({
					nickname: that.nicknameInputVal
				});
				that.user.nickname = that.nicknameInputVal;
				app.globalData.config.storage.setUserInfoData(that.user);
				uni.showToast({
					title: res.message,
					mask: true,
					complete: function() {
						setTimeout(function() {
							uni.navigateBack();
						}, 500);
					}
				});
			},
			cancelTap() {
				uni.navigateBack();
			}
		}
	};
</script>
<style>
	button:after {
		border: none;
	}
	
	.content-wrapper {
		padding: 30rpx;
	}
	
	.avatar-section {
		display: flex;
		justify-content: center;
		padding: 40rpx 0;
		background: linear-gradient(45deg, #0081ff, #1cbbb4);
		border-radius: 0 0 50rpx 50rpx;
		margin-bottom: 40rpx;
	}
	
	.avatar-button {
		background: transparent;
		padding: 0;
		width: auto;
		height: auto;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.cu-avatar.xl {
		width: 160rpx;
		height: 160rpx;
		border: 6rpx solid rgba(255, 255, 255, 0.7);
		box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);
	}
	
	.avatar-hint {
		color: #ffffff;
		font-size: 24rpx;
		margin-top: 20rpx;
		opacity: 0.9;
	}
	
	.form-section {
		margin: 30rpx 0 60rpx;
	}
	
	.cu-form-group {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 30rpx;
		border-radius: 12rpx;
		box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);
	}
	
	.cu-form-group .title {
		font-weight: bold;
	}
	
	.button-section {
		padding: 20rpx 0 40rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		gap: 30rpx;
	}
	
	.cu-btn {
		margin-bottom: 0;
		height: 90rpx;
		font-size: 32rpx;
		font-weight: bold;
		letter-spacing: 2rpx;
		line-height: 90rpx;
		min-width: 220rpx;
		box-sizing: border-box;
	}
	
	.cu-btn.bg-gradual-blue,
	.cu-btn.bg-grey {
		box-shadow: 0 10rpx 20rpx rgba(0, 129, 255, 0.2);
	}
</style>